import mqtt from 'mqtt/dist/mqtt.js' //引入mqtt依赖

var client                          
let mqttConnected = false  //mqtt连接状态，这个可以不要，直接查询client.connected即可
const publishTopic = ''  //发布Topic
const subTopics = ['szls_tc/connect_disconnected','tcxt/mqttx_95b54201/dev','tcxt/mqttx_95b54202/dev','tcxt/mqttx_95b54203/dev','tcxt/mqttx_95b54204/dev','tcxt/mqttx_95b54205/dev','tcxt/mqttx_95b54206/dev','tcxt/mqttx_95b54207/dev','tcxt/mqttx_95b54208/dev']
// const subTopics = ['szls_tc/connect_disconnected','tcxt/+/dev']
const MQTT_IP = '47.104.161.160:8083/mqtt' //mqtt地址端口
const timestamp = Date.now(); // 输出示例：1713772800000 :ml-citation{ref="7,8" data="citationList"}
const MQTT_OPTIONS = {
    connectTimeout: 30000,      //连接超时时间
    clientId: 'SiD0FMMAxrs_'+timestamp,  //clientId不能重复，这里可以随机生成
    username: 'tcxt_client',         //用户名
    password: 'tcxt_client123456!',         //密码
    clean: false,
	reconnectPeriod: 1000,
	sessionExpiryInterval: 1,
	keepalive: 30,
	resubscribe: true,
}

//创建客户端连接
export function mqttConnect() {
	// #ifdef H5
	client = mqtt.connect('ws://' + MQTT_IP, MQTT_OPTIONS,function(err){
		console.log(err)
	})
	// #endif
	// #ifdef MP-WEIXIN||APP-PLUS
	client = mqtt.connect('wx://' + MQTT_IP, MQTT_OPTIONS,function(err){
		console.log(err)
	})
	// #endif

	client.on('connect', function() {
	    console.log('连接成功')
		mqttConnected = true
	}).on('reconnect', function(error) {
	    console.log('正在重连...', error)
		mqttConnected = false
	}).on('error', function(error) {
	    console.log('连接失败...', error)
		mqttConnected = false
	}).on('end', function() {
	    console.log('连接断开')
		mqttConnected = false
	}).on('close',function(){
		console.log('连接关闭')
		mqttConnected = false
	}).on('offline',function(){
		console.log('客户端下线')
	})
	//多主题
	client.subscribe(subTopics, { qos: 1 }, (err) => {
	    if(!err) console.log('订阅成功')
	})
	//单主题
	// client.subscribe(subTopic, {
	// 	qos: 1
	// }, function(err, res) {
	// 	if (!err && res.length > 0) {
	// 		console.log('App_text' + ":subscribe success 订阅成功")
	// 	} else {
	// 		console.log('App_text' + ":subscribe failed 订阅失败")
	// 		return;
	// 	}
	// })
	client.on('message',(topic,payload)=>{
		console.log(`收到${topic}消息:`, payload.toString())
		const message = payload.toString();
		// uni.$emit('mqtt-message', { topic, message });
		if(topic == 'szls_tc/connect_disconnected'){
			uni.$emit('mqtt-status',{ topic, message })
		}else{
			uni.$emit('mqtt-message', { topic, message });
		}
	})
}
// export function mqttSubscribe(){
// 	client.subscribe(subTopic, {
// 		qos: 1
// 	}, function(err, res) {
// 		console.log(err, res)
// 		if (!err && res.length > 0) {
// 			resolve('订阅成功')
// 			console.log('App_text' + ":subscribe success 订阅成功")
// 		} else {
// 			resolve('订阅失败')
// 			console.log('App_text' + ":subscribe failed 订阅失败")
// 			return;
// 		}
// 	})
// }
//发布消息
export function mqttPublish(msg){
	if(mqttConnected){
		client.publish(publishTopic,msg,{qos:1,retain:false});//hello mqtt +
		console.log('发布了一条消息',msg)
	}else{
		uni.showToast({
			title: 'MQTT服务器未连接',
			icon: 'none'
		});
	}
}
//断开连接
export function mqttDisconnect(){
	console.log('mqttConnected',mqttConnected)
	console.log('client',client)
	if(mqttConnected){
		client.end(true)
		mqttConnected = false
	}
	
}
